package com.mobis.base.service;


import com.mobis.base.dao.LabelDao;
import com.mobis.base.pojo.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class LabelService {

    @Autowired
    private LabelDao labelDao;

    public List<Label> findAllLabel(){
        return labelDao.findAll();
    }

    public Label findById(String id){
        return labelDao.findById(id).get();
    }

    public void addLabel(Label label){
        labelDao.save(label);
    }

    public void deleteLabel(Label label){
        labelDao.delete(label);
    }

    public List<Label> findSearch(Label label){
        return labelDao.findAll(new Specification<Label>() {
            /**
             *
             * @param root  把对象封装到那个里面
             * @param criteriaQuery  封装的查询关键字
             * @param criteriaBuilder  用来封装对象的
             * @return
             */
            @Override
            public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //用来封装查询条件
                List<Predicate> list=new ArrayList<>();

                if (label.getLabelname()!=null&&!"".equals(label.getLabelname())){
                    Predicate predicate=criteriaBuilder.like(root.get("labelname").as(String.class),"%"+label.getLabelname()+"%");
                    list.add(predicate);
                }

                if (label.getLabelname()!=null&&!"".equals(label.getLabelname())){
                    Predicate predicate=criteriaBuilder.like(root.get("state").as(String.class),"%"+label.getState()+"%");
                    list.add(predicate);
                }
                Predicate[] predicates=new Predicate[list.size()];
                list.toArray(predicates);
                return criteriaBuilder.and(predicates);
            }
        });
    }


}
